<?php


namespace app\controller\admin;


use app\BaseController;
use app\common\Consts;
use app\models\user\AdminUserModel;
use app\services\area\RegionService;
use app\services\cupboard\OperatorService;
use app\services\delivery\DeliveryService;
use app\services\utils\RedisService;
use app\services\user\AdminUserService;
use think\Exception;
use think\facade\Db;
use think\Request;
use app\models\user\AdminRoleModel;


class UserController extends BaseController
{


    /**
     * 用户信息
     * @param Request $request
     * @return \think\response\Json
     */
    public function info(Request $request)
    {
        return $this->success($request->userInfo);
    }

    /**
     * 退出登录
     * @param Request $request
     * @return \think\response\Json
     */
    public function logout(Request $request)
    {
        try {
            $tokenExpireTime = $request->expireTime;
            $timeOut = $tokenExpireTime - time();
            RedisService::instance()->setex($request->header('token'), $timeOut, $tokenExpireTime);
            //更新token 和 过期时间
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 添加管理员
     * @param Request $request
     * @return \think\response\Json
     */
    public function add(Request $request)
    {
        try {
            $id = $request->param('id', 0);
            $data = $request->only(['nick', 'username', 'password', 'role_id', 'avatar', 'department_id', 'pid','shop_id'], 'param', 'trim');
            if (!$id) {
                // 判断账号是否存在
                $userInfo = AdminUserService::getUserByAccount($data['username']);
                if ($userInfo) {
                    throw new \Exception('账号已存在');
                }
                // 添加账号
                $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
                if (isset($data['pid']) && $data['pid']) {
                    $pinfo = AdminUserModel::find($data['pid']);
                    $referrer = $pinfo['referrer'] . $pinfo['id'] . ',';
                    $data['referrer'] = $referrer;
                }
                $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
                AdminUserService::createUser($data);
                return $this->success();
            } else {
                // 判断账号是否存在
                $userInfo = AdminUserService::getUserInfo($data['username']);
                if ($userInfo && $userInfo['id'] != $id) {
                    throw new \Exception('账号已存在');
                }
                // 编辑账号
                if (isset($data['password']) && $data['password']) {
                    $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
                } else {
                    unset($data['password']);
                }
                AdminUserService::saveUser($id, $data);
                return $this->success();
            }
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 获取用户列表
     * @param Request $request
     * @return \think\response\Json
     */
    public function getUserList(Request $request)
    {
        try {
            $userInfo = $request->userInfo;
            $roleId = $userInfo->role_id;
            $where = [];
            $where[] = ['status', '=', 0];

            $params = $request->param();
            if (isset($params['nick'])) {
                $where[] = ['nick', 'like', '%' . trim($params['nick']) . '%'];
            }
            if (isset($params['username'])) {
                $where[] = ['username', 'like', '%' . trim($params['username']) . '%'];
            }
            if (isset($params['role_id'])) {
                $where[] = ['role_id', '=', $params['role_id']];
            }
            if ($roleId != Consts::ADMIN_ROLE_ID) {
                $roleIdArr = AdminRoleModel::where('referrer','like','%'.$roleId.'%')->column('id');
                $where[] = ['role_id', 'in', $roleIdArr];
            }
            $list = AdminUserModel::with(['role'])
                ->where($where)
                ->order('id', 'desc')
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->toArray();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 禁用、启用用户
     * @param Request $request
     * @return \think\response\Json
     */
    public function status(Request $request)
    {
        try {
            $id = $request->param('id');
            if (!$id) {
                throw new \Exception('缺少参数');
            }
            $status = !$request->param('status') ? 1 : 0;
            Db::name('admin_user')->where('id', $id)->update(['status' => $status, 'update_time' => date('Y-m-d H:i:s')]);
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 删除用户
     * @param Request $request
     * @return \think\response\Json
     */
    public function del(Request $request)
    {
        try {
            Db::startTrans();
            $id = $request->param('id');
            if (!$id) {
                throw new \Exception('缺少参数');
            }
            Db::name('admin_user')->where('id', $id)->delete();
            event('syncUser', ['operate' => 'del', 'id' => $id]);
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    public function setUserInfo()
    {
        try {
            $userInfo = $this->request->userInfo;
            $id = $this->request->param('id');
            $nick = $this->request->param('nick', '', 'trim');
            $avatar = $this->request->param('avatar');
            $pwd = $this->request->param('password', '', 'trim');
            $id = $id == 0 ? $userInfo['id'] : $id;
            $userInfo = AdminUserModel::find($id);
            if (!$userInfo) {
                throw new \Exception('用户不存在');
            }
            if($avatar){
                $userInfo->avatar = $avatar;
            }
            if($nick){
                $userInfo->nick = $nick;
            }
            $userInfo->update_time = date('Y-m-d H:i:s');
            if ($pwd) {
                $userInfo->password = password_hash($pwd, PASSWORD_DEFAULT);
            }
            $userInfo->save();
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    public function getUserListByDepartment(Request $request)
    {
        try {
            Db::startTrans();
            $did = $request->param('department_id');
            $list = Db::name('admin_user')
                ->field('id,nick')
                ->where('department_id', $did)
                ->where('status', 0)
                ->select();
            Db::commit();
            return $this->success($list);
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    public function getUserInfo()
    {
        return $this->request->userInfo;
    }


    /**
     * 提现记录
     * @return \think\response\Json
     */
    public function getAuthenticationList()
    {
        try {
            $status = $this->request->param('status');
            $where = [];
            if($status){
                $where[] = ['status','=',$status];
            }
            $user_name = $this->request->param('user_name');
            if($user_name){
                $where[] = ['name|phone','like',"%{$status}%"];
            }
            $start_time = $this->request->param('start_time');
            if($start_time){
                $where[] = ['create_time','>',strtotime($start_time)];
            }
            $end_time = $this->request->param('end_time');
            if($end_time){
                $where[] = ['create_time','<',strtotime($end_time)];
            }

            $order_by = $this->request->param('order_by','id');
            $sort = $this->request->param('sort','desc');

            $limit = $this->request->param('limit');
            $page = $this->request->param('page');
            $list = Db::name('user_authentication')->where($where)
                ->order($order_by, $sort)
                ->paginate(['list_rows' => $limit, 'page' => $page])
                ->toArray();
            foreach ($list['data'] as &$value) {
                $userInfo = Db::name('user')->find($value['user_id']);
                $value['user_name'] = $userInfo['nick'] ?? '';
                $value['mobile'] = $userInfo['mobile'] ?? '';
                $value['create_time'] = date('Y-m-d H:i:s',$value['create_time']);
                if($value['audit_time']){
                    $value['audit_time'] = date('Y-m-d H:i:s',$value['audit_time']);
                }
            }
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 提现记录
     * @return \think\response\Json
     */
    public function authenticationAudit()
    {
        try {
            $id = $this->request->param('id');
            $status = $this->request->param('status'); //状态： 1=已审核
            $reason = $this->request->param('reason', '', 'trim');
            $info = Db::name('user_authentication')->find($id);
            if (!$info) {
                throw new \Exception("实名认证信息不存在");
            }
            if ($info['status'] != 0) {
                throw new \Exception("信息已审核");
            }
            Db::name('user_authentication')->where('id',$info['id'])->update([
                'status' => $status,
                'remark' => $reason,
                'audit_time' => time(),
                'update_time' => time()
            ]);
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }
}
